package cn.zj.smart.util.net;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xi.yang
 * @create 2021-10-21 17:40
 **/
public class HttpUtil {
    private static final int STATUS_OK = 200;
    private static final String CHAR_SET = "UTF-8";
    private static HttpClient httpClient;

    public static String get(String url) {
        return get(url, null, null);
    }

    public static String get(String url, Map<String, String> header, Map<String, String> params) {
        if (httpClient == null) {
            httpClient = HttpClients.custom().build();
        }
        HttpGet httpGet = new HttpGet(url);
        if (null != header) {
            header.forEach(httpGet::addHeader);
        }
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == STATUS_OK) {
                return EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url) {
        return post(url, null, null);
    }

    public static String post(String url, Map<String, String> header, Map<String, String> params) {
        if (httpClient == null) {
            httpClient = HttpClients.custom().build();
        }
        HttpPost httpPost = new HttpPost(url);
        if (null != header) {
            header.forEach(httpPost::addHeader);
        }
        List<NameValuePair> nvps = new ArrayList<>();
        if (params != null) {
            params.forEach((k, v) -> nvps.add(new BasicNameValuePair(k, v)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, CHAR_SET));
            HttpResponse result = httpClient.execute(httpPost);
            if (result.getStatusLine().getStatusCode() == STATUS_OK) {
                return EntityUtils.toString(result.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
